package com.xcm.scheduled;

import com.alibaba.fastjson.JSONObject;
import com.xcm.config.CustomProperties;
import com.xcm.constant.BusinessConstant;
import com.xcm.constant.FileConstant;
import com.xcm.exception.ServiceException;
import com.xcm.model.TbProgramJsonAuthFailDetail;
import com.xcm.model.dto.AuthProgramJsonDTO;
import com.xcm.model.dto.BottomProgramDTO;
import com.xcm.model.dto.TopProgramDTO;
import com.xcm.service.ProgramBottomService;
import com.xcm.service.ProgramJsonAuthFailDetailService;
import com.xcm.service.ProgramJsonService;
import com.xcm.service.ProgramTopService;
import com.xcm.util.ValidateProgramJsonUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class ValidateProgramJsonTasks {

	private static Logger logger = LoggerFactory.getLogger(ValidateProgramJsonTasks.class);
	@Autowired
	private ProgramTopService programTopService;
	@Autowired
	private ProgramBottomService programBottomService;
	@Autowired
	private ProgramJsonService programJsonService;
	@Autowired
	private ProgramJsonAuthFailDetailService programJsonAuthFailDetailService;
	@Autowired
	private CustomProperties customProperties;
	/**
	 * 文件下载临时存储目录
	 */
	private String fileDownloadTempStoreDir;
	/**
	 * 验证节目
	 */
//	@Scheduled(cron = "")
	public void validateProgramJson() {
		List<AuthProgramJsonDTO> authNoPassProgramJsonList = programJsonService.listAuthNoPassProgramJson();
		//文件不存在
		StringBuilder fileNotFoundSb = new StringBuilder();
		//视频时长不合法
		StringBuilder videoDurationIllegalSb = new StringBuilder();
		//文件名为空
		StringBuilder fileNameIsNullSb = new StringBuilder();
		//文件URL为空
		StringBuilder fileURLIsNullSb = new StringBuilder();
		//视频时长为空
		StringBuilder videoDurationIsNullSb = new StringBuilder();
		if (CollectionUtils.isNotEmpty(authNoPassProgramJsonList)) {
			for (int i = 0; i < authNoPassProgramJsonList.size(); i++) {
				AuthProgramJsonDTO dto = authNoPassProgramJsonList.get(i);
				String xcVersion = dto.getXcVersion();
				if (StringUtils.isBlank(xcVersion)) {
					continue;
				}
				//上屏节目列表
				List<TopProgramDTO> topList = programTopService.listTopProgramDTOByXcVersion(xcVersion);
				//下屏节目列表
				List<BottomProgramDTO> bottomList = programBottomService.listBottomProgramDTOByXcVersion(xcVersion);
				//校验上下屏节目
				Map<String, Integer> msgMap =  ValidateProgramJsonUtils.validateProgram(xcVersion, topList, bottomList);
				//返回信息map的size大于0，校验不通过
				if (msgMap.size() > 0) {
					for (Map.Entry<String, Integer> entry : msgMap.entrySet()) {
						int value = entry.getValue().intValue();
						String key = entry.getKey();
						//文件不存
						if (FileConstant.FILE_NOT_FOUND == value) {
							if (fileNotFoundSb.length() > 0) {
								fileNotFoundSb.append(",");
							}
							fileNotFoundSb.append(key);
						}
						//视频时长不合法
						if (FileConstant.VIDEO_DURATION_ILLEGAL == value) {
							if (videoDurationIllegalSb.length() > 0) {
								videoDurationIllegalSb.append(",");
							}
							fileNotFoundSb.append(key);
						}
						//文件名为空
						if (FileConstant.FILE_NAME_IS_NULL == value) {
							if (fileNameIsNullSb.length() > 0) {
								fileNameIsNullSb.append(",");
							}
							fileNameIsNullSb.append(key);
						}
						//文件URL地址为空
						if (FileConstant.FILE_URL_IS_NULL == value) {
							if (fileURLIsNullSb.length() > 0) {
								fileURLIsNullSb.append(",");
							}
							fileURLIsNullSb.append(key);
						}
						//视频时长为空
						if (FileConstant.VIDEO_DURATION_IS_NULL == value) {
							if (videoDurationIsNullSb.length() > 0) {
								videoDurationIsNullSb.append(",");
							}
							videoDurationIsNullSb.append(key);
						}
					}
					//保存验证不通过的详情
					TbProgramJsonAuthFailDetail programJsonAuthFailDetail = new TbProgramJsonAuthFailDetail();
					programJsonAuthFailDetail.setXcVersion(xcVersion);
					JSONObject jsonObject = new JSONObject();
					jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_FILE_NOT_FOUND, fileNotFoundSb.toString());
					jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_VIDEO_DURATION_ILLEGAL, videoDurationIllegalSb.toString());
					jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_FILE_NAME_IS_NULL, fileNameIsNullSb.toString());
					jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_FILE_URL_IS_NULL, fileURLIsNullSb.toString());
					jsonObject.put(BusinessConstant.VALIDATE_PROGRAM_VIDEO_DURATION_IS_NULL, videoDurationIsNullSb.toString());
					programJsonAuthFailDetail.setAuthFailDetail(jsonObject.toJSONString());
					try {
						programJsonAuthFailDetailService.saveProgramJsonAuthFailDetail(programJsonAuthFailDetail);
					} catch (ServiceException e) {
						e.printStackTrace();
						logger.error("ValidateProgramJsonTasks 保存节目json校验失败详情失败；" + e.getMessage());
					}
				} else {
					programJsonService.updateProgramJsonAuthByXcVersion(BusinessConstant.PROGRAMJSON_AUTH_STATE_SUCESS, xcVersion);
				}
				//重新初始化
				fileNotFoundSb.setLength(0);
				videoDurationIllegalSb.setLength(0);
				fileNameIsNullSb.setLength(0);
				fileURLIsNullSb.setLength(0);
				videoDurationIsNullSb.setLength(0);
				//校验完后，删除文件目录及目录下的所有文件
				fileDownloadTempStoreDir = customProperties.getFileDownloadTempStoreDir();
				String separator = File.separator;
				if (fileDownloadTempStoreDir.endsWith(separator)) {
					fileDownloadTempStoreDir = fileDownloadTempStoreDir + xcVersion;
				} else {
					fileDownloadTempStoreDir = fileDownloadTempStoreDir + separator + xcVersion;
				}
				File tempFile = new File(fileDownloadTempStoreDir);
				if (tempFile.exists()) {
					try {
						FileUtils.deleteDirectory(tempFile);
					} catch (IOException e) {
						logger.error("ValidateProgramJsonTasks: " + e.getMessage());
						e.printStackTrace();
					}
				}
			}
		}
	}

}
